<template>
  <div class="tags">
    <!-- 面包屑导航区 -->
    <el-card class="breadcrumb-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item
          ><a href="/#/manager/home">首页</a></el-breadcrumb-item
        >
        <el-breadcrumb-item>标签管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <!-- 卡片视图 -->
    <el-card class="tag-list">
      <!-- 表格 -->
      <vxe-table
        resizable
        border
        ref="xTree"
        :tree-config="{ children: 'children' }"
        :edit-config="{ trigger: 'click', mode: 'row' }"
        :checkbox-config="{ labelField: 'id' }"
        :data="tagList"
        v-loading="loading"
        element-loading-text="Loading..."
      >
        <vxe-table-column
          type="seq"
          width="120"
          title="序号"
          header-align="center"
          tree-node
        ></vxe-table-column>
        <vxe-table-column
          field="tagName"
          title="标签名称"
          align="center"
        ></vxe-table-column>
        <vxe-table-column title="是否有效" align="center">
          <template v-slot="scope">
            <el-icon
              v-if="scope.row.tagDeleted !== true"
              style="color: lightgreen"
            >
              <CircleCheck />
            </el-icon>
            <el-icon v-else style="color: lightcoral">
              <CircleClose />
            </el-icon>
          </template>
        </vxe-table-column>
        <vxe-table-column title="标签级" align="center">
          <template v-slot="scope">
            <el-tag v-if="scope.row.tagLevel === 0">一级</el-tag>
            <el-tag v-else-if="scope.row.tagLevel === 1" type="success"
              >二级</el-tag
            >
            <el-tag v-else type="warning">三级</el-tag>
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" align="center">
          <template slot="operation" #default="scope">
            <el-button
              type="success"
              :icon="CirclePlus"
              @click="showAddTagDialog(scope.row.tagName)"
              v-show="tagModules.indexOf(scope.row.tagName) !== -1 ? true : false"
              >新增</el-button
            >
            <el-button
              type="danger"
              :icon="Delete"
              @click="deleteTag(scope.row.tagName)"
              v-show="tagModules.indexOf(scope.row.tagName) !== -1 ? false : true"
              >删除</el-button
            >
          </template>
        </vxe-table-column>
      </vxe-table>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加标签"
      v-model="addTagDialogVisible"
      @close="addTagDialogClosed(addTagFormRef)"
      width="50%"
      v-loading="loadingDialog"
      element-loading-text="Loading..."
      style="text-align: left;"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addTagForm"
        :rules="addTagFormRules"
        ref="addTagFormRef"
        label-width="130px"
      >
        <el-form-item label="新增标签名称：" prop="tagContent">
          <el-input
            placeholder="请输入新增标签"
            v-model="addTagForm.tagContent"
          ></el-input>
        </el-form-item>
        <el-form-item label="标签模块：" prop="tagModuleId">
          <el-select
            v-model="addTagForm.tagModuleId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in tagModuleOptions"
              :key="item.tagModuleId"
              :label="item.tagModuleName"
              :value="item.tagModuleId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="footer">
        <el-button @click="addTagDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTag(addTagFormRef)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { FormRules, FormInstance, ElMessage, ElMessageBox } from 'element-plus';
import { CircleCheck, CircleClose, CirclePlus, Delete } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, ComponentInternalInstance, onMounted, reactive } from 'vue';

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 标签列表
interface TagList {
  tagId: Number
  tagName: String
  tagDeleted: Boolean
  tagLevel: Number
  children: [{
    tagId: Number
    tagName: String
    tagDeleted: Boolean
    tagLevel: Number
  }]
};
const tagList = ref<TagList[]>([]);
// 加载
const loading = ref(false);
const loadingDialog = ref(false);
// 控制添加分类对话框的显示与隐藏
const addTagDialogVisible = ref(false);
// 添加标签的表单数据对象
let addTagForm = reactive({
  // 将要添加的标签的名称
  tagContent: '',
  // 标签模块的id
  tagModuleId: 0,
  tagName: ''
});
// 验证规则
const addTagFormRules = reactive<FormRules>({
  tagContent: [
    {
      required: true,
      message: '请输入分类名称',
      trigger: ['blur', 'change'],
    },
  ],
  tagModuleId: [
    {
      required: true,
      message: '请选择标签模板',
      trigger: ['blur', 'change'],
    },
  ],
});
const addTagFormRef = ref();
// 标签模块信息
interface TagModuleOptions {
  tagModuleId: Number
  tagModuleName: String
}
const tagModuleOptions = ref<TagModuleOptions[]>([]);
// 所有标签
interface Tags {
  tagContent: String
  tagName: String
}
const tags = ref<Tags[]>([]) as any;
// 所有标签模块
interface TagModules {
  tagModuleName: String
}
const tagModules = ref<TagModules[]>([]);

onMounted(() => {
  getTagList();
})

// 获取所有标签
function getTagList() {
  loading.value = true;
  proxy.$request.tag.getAllTag().then((res: any) => {
    tagList.value = [];
    tagModuleOptions.value = [];
    tags.value = [];
    tagModules.value = [];
    res.data.forEach((item: any, index: any) => {
      tagModuleOptions.value.push({
        tagModuleId: item.tagModuleId,
        tagModuleName: item.tagModuleName,
      });
      tagModules.value.push(item.tagModuleName);
      tagList.value.push({
        tagId: item.tagModuleId,
        tagName: item.tagModuleName,
        tagDeleted: false,
        tagLevel: 0,
        children: [] as any,
      });
      res.data[index].tagList.forEach((item: any) => {
        tags.value.push(item.tagContent);
        tagList.value[index].children.push({
          tagId: item.tagId,
          tagName: item.tagContent,
          tagDeleted: false,
          tagLevel: 1,
        });
      });
    });
    loading.value = false;
  });
};
// 展示添加标签对话框
function showAddTagDialog(tagName: any) {
  addTagDialogVisible.value = true;
  addTagForm.tagModuleId = tagModules.value.indexOf(tagName) + 1;
};
// 监听添加标签对话框的关闭事件
function addTagDialogClosed(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
};
// 添加标签
function addTag(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    if (tags.value.indexOf(addTagForm.tagName) !== -1) {
      addTagForm = {
        tagContent: '',
        tagModuleId: 0,
        tagName: ''
      };
      return ElMessage({
        message: '新增标签名与原有标签重复',
        type: 'error',
        duration: 1000,
      });
    }
    loadingDialog.value = true;
    proxy.$request.tag.addTag(addTagForm).then((res: any) => {
      ElMessage({
        message: res.msg,
        type: 'success',
        duration: 1000,
      });
      getTagList();
      formEl.resetFields();
      loadingDialog.value = false;
      addTagDialogVisible.value = false;
    });
  });
};
// 删除标签
function deleteTag(tagName: String) {
  ElMessageBox.confirm(
    '此操作将删除（ <strong>' + tagName + '</strong> ）标签, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      loading.value = true;
      tagList.value.forEach((item) => {
        item.children.forEach((itemChildren) => {
          if (itemChildren.tagName === tagName) {
            proxy.$request.manager
              .deleteTag({
                tagContent: tagName,
                tagId: itemChildren.tagId,
                tagModuleId: item.tagId,
              })
              .then((res: any) => {
                ElMessage({
                  type: 'success',
                  message: res.msg,
                  duration: 1000,
                });
                getTagList();
              });
          }
        });
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
        duration: 1000,
      });
    });
};
</script>

<style lang="less" scoped>
.breadcrumb-box {
  height: 36px;
  border-radius: 0;
  padding: 0 20px;
  border: 0;
  margin: 0 0 20px !important;
  position: fixed;
  top: 60px;
  width: 100%;
  z-index: 9;

  .el-breadcrumb {
    line-height: 36px;
  }

  /deep/ .el-card__body {
    padding: 0;
  }
}

.tag-list {
  margin: 60px 20px 0;
}

.footer {
  display: flex;
  justify-content: end;
  width: 100%;
  margin-top: 20px;
}
</style>
